import hashlib
import logging
import random
import re
import string

from pypinyin import lazy_pinyin

log = logging.getLogger(__name__)


# 只保留汉字、数字、字母、下划线、-
def filter_name(name, default=''):
    if name is None:
        return default
    if name == '':
        return default
    name = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9_-]', '', name)
    return name


# 检验是否为合法的名称，只能包含汉字、数字、字母、下划线、-,且最长为48个字符
def is_valid_name(name):
    if name is None:
        return False
    if name == '':
        return False
    if len(name) > 48:
        return False
    if re.search(r'[^\u4e00-\u9fa5a-zA-Z0-9_-]', name):
        return False
    return True


# 长度为size的随机字符串
def id_generator(size=4, chars=string.ascii_letters + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))


# 中文转拼音,仅保留数字、字母、-
def convert_to_pinyin(name, max_length=20):
    pattern = r'[^a-zA-Z0-9-]+'
    ret = ''.join(lazy_pinyin(name))
    ret = re.sub(pattern, '', ret)
    return ret[:max_length]


def is_valid_email(email):
    if email is None:
        return False
    if len(email) == 0:
        return False
    # 正则表达式匹配电子邮箱
    pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
    return bool(pattern.match(email))


def is_valid_phone_number(number):
    if number is None:
        return False
    if len(number) == 0:
        return False
    # 正则表达式匹配中国大陆电话号码
    pattern = re.compile(r'^(?:\+86)?1[3-9]\d{9}$')
    return bool(pattern.match(number))


def md5(s):
    md5_hash = hashlib.md5()
    md5_hash.update(s.encode('utf-8'))
    val = md5_hash.hexdigest()
    return val
